package com.hmdp.consumer;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.SeckillVoucherMapper;
import com.hmdp.service.IVoucherOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import static com.hmdp.utils.RedisConstants.SECKILL_STOCK_KEY;

@Component
@RequiredArgsConstructor
@Slf4j
public class VoucherOrderConsumer {

    private final IVoucherOrderService voucherOrderService;

    private final RedisTemplate<String, Object> redisTemplate;

    private final SeckillVoucherMapper seckillVoucherMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "seckill.queue", durable = "true"),
            exchange = @Exchange(value = "seckill.exchange", type = ExchangeTypes.TOPIC),
            key = "seckill.#"
    ))
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        voucherOrderService.save(voucherOrder);
        Integer stock = (Integer) redisTemplate.opsForValue().get(SECKILL_STOCK_KEY + voucherOrder.getVoucherId());
        LambdaUpdateWrapper<SeckillVoucher> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SeckillVoucher::getStock, stock)
                .setSql("stock = stock - 1")
                .eq(SeckillVoucher::getVoucherId, voucherOrder.getVoucherId())
                .gt(SeckillVoucher::getStock, 0);
        int count = seckillVoucherMapper.update(null, updateWrapper);
        if (count == 0) {
            log.warn("数据库库存更新失败，voucherId: {}", voucherOrder.getVoucherId());
        }
    }
}
